package org.fuys.coder.infrastructure.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.fuys.coder.domain.favorites.repository.IUserFavoriteRepository;
import org.fuys.coder.infrastructure.dao.FavoriteUserMapper;
import org.fuys.coder.infrastructure.model.po.FavoritesUser;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @projectName: fuys-low-coder
 * @package: org.fuys.coder.infrastructure.repository
 * @className: IUserFavoriteRepositoryImpl
 * @author: WangJing
 * @description: 用户收藏夹仓储实现
 * @date: 2024/6/19 18:20
 * @version: 1.0
 */
@Service
public class UserFavoriteRepositoryImpl extends ServiceImpl<FavoriteUserMapper,FavoritesUser>
        implements IUserFavoriteRepository {

    @Resource
    private FavoriteUserMapper favoriteUserMapper;

    @Override
    public boolean saveRecord(Integer userId, Long favoriteId) {
        try {
            FavoritesUser favoritesUser=new FavoritesUser();
            favoritesUser.setFavoritesId(favoriteId);
            favoritesUser.setUserId(userId);
            this.save(favoritesUser);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean checkBelong(Integer userId, Long favId) {
        final FavoritesUser favoritesUser = favoriteUserMapper.selectOne(new LambdaQueryWrapper<FavoritesUser>()
                .select(FavoritesUser::getId).eq(FavoritesUser::getUserId, userId)
                .eq(FavoritesUser::getFavoritesId, favId));
        return favoritesUser != null;
    }

    @Override
    public List<Long> getUserFavIds(Integer userId) {
        final List<FavoritesUser> favoritesUsers = favoriteUserMapper.selectList(new LambdaQueryWrapper<FavoritesUser>()
                .select(FavoritesUser::getFavoritesId)
                .eq(FavoritesUser::getUserId, userId));
        if(ObjectUtils.isEmpty(favoritesUsers)){
            return null;
        }
        return favoritesUsers.stream().map(FavoritesUser::getFavoritesId).collect(Collectors.toList());
    }
}
